package cn.edu;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.junit.Test;

import java.util.Date;

/**
 * @PackageName: cn.edu
 * @ClassName: CreateTocken
 * @Description:
 * @author: RZS
 * @date: 2021/7/14  17:39
 */
public class CreateToken {


    /**
     * 生成token
     */
    @Test
    public void token(){
        // 构建令牌JWT对象
        JWTCreator.Builder builder = JWT.create();
        // 设置自定义用户名
        builder.withClaim("username", "大锤");
        // 设置签发时间
        builder.withIssuedAt(new Date(System.currentTimeMillis()));
        // 设置过期时间
        builder.withExpiresAt(new Date(System.currentTimeMillis()+60*1000*3));
        // 设置签名
        String token = builder.sign(Algorithm.HMAC256("dc"));
        System.out.println(token);
    }

    /**
     * 解析token
     */
    @Test
    public void resolverToken(){
        // 黄键解析对象
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("dc")).build();
        // 解析token
        DecodedJWT verify = jwtVerifier.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MjYyNjk1NzYsImlhdCI6MTYyNjI2OTM5NiwidXNlcm5hbWUiOiLlpKfplKQifQ.EKCq9hkrEN2yxxi2qX7R2Aj1wf9RD4ninvmyNGBpILE");
        // 获取用户名
        System.out.println(verify.getClaim("username").asString());
        // 获取token失效时间
        System.out.println(verify.getExpiresAt());
        // 获取用户名
        System.out.println(verify.getClaims().get("username").asString());
    }


}
